import os.path
import time

from django.shortcuts import render, redirect,HttpResponse
from django.http import HttpResponseRedirect
from django.views import View
from .models import Press, BookType
from django.db.models import Q
from app.models import Admin,Press,Book
from django.contrib import messages
from django.utils.decorators import method_decorator
# Create your views here.

def login_decorator(fun):
    def inner(request,*args,**kwargs):
        # 判断用户是否登录
        if request.session.get("login"):
            # 如果满足，则正常访问
            return fun(request, *args, **kwargs)
        messages.warning(request,"登录信息已过期，请重新登录！")
        return redirect('/login/')
    return inner
def login(request):
    """
    :info 这是一个登录
    :param request
    :version: 1.0
    """
    if request.method == "GET":
        return render(request, 'login.html')
    elif request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')
        if Admin.objects.filter(username=username, password=password):
            response = redirect('/main/')
            # 设置响应cookie
            response.set_cookie('login','OK')
            # 设置session
            request.session['login'] = 'OK'

            return response
        else:
            return render(request, 'login.html', {'msg': '用户名或密码错误！'})
@login_decorator
def pressadd(request):
    if request.method == "GET":
        return render(request, 'pressadd.html')
    elif request.method == "POST":
        # 获取数据   从页面出发，回归页面
        pressname = request.POST.get('pressname')
        pressaddress = request.POST.get('pressaddress')

        # 调用ORM，执行添加请求
        Press.objects.create(pressname=pressname,pressaddress=pressaddress)

        # 跳转页面
        return redirect('/booklist')



def code_time(func):
    def wrapper(*args, **kwargs):
        print("开始执行")
        start_time = time.time()
        result = func(*args, **kwargs)  # 保存 func 的执行结果
        end_time = time.time()
        print("结束执行")
        print("耗时：", end_time - start_time)
        return result  # 返回 func 的执行结果
    return wrapper


#登录装饰器





@login_decorator
def pressdelete(request):
    # 获取参数
    id = request.GET.get('id')

    # 调用orm
    Press.objects.filter(id=id).delete()

    # 跳转页面
    return redirect('/presslist')
@login_decorator
def pressupdate(request):
    if request.method == "GET":
        # 获取参数
        id = request.GET.get('id')

        # 调用orm - 使用get()获取单个对象
        press = Press.objects.get(id=id)

        # 跳转页面 修改页面 转发
        return render(request, 'pressupdate.html', {'press': press})
    elif request.method == "POST":
        id = request.POST.get('id')
        pressname = request.POST.get('pressname')
        pressaddress = request.POST.get('pressaddress')

        # 真正的修改
        # 第一步：通过id找到orm对象
        press = Press.objects.get(id=id)

        # 第二步:通过orm对象（持久化对象）进行修改属性
        press.pressname = pressname
        press.pressaddress = pressaddress

        # 第三步：执行持久化方法，完成修改
        press.save()
        return redirect('/presslist')

@login_decorator
def presssearch(request):
    # 获取参数
    pressname = request.POST.get('pressname')
    # 调用orm
    presslist = Press.objects.filter(pressname__icontains=pressname)
    # 跳转页面
    return render(request, 'presslist.html', {'presslist': presslist,'pressname':pressname})

@login_decorator
def presslist(request):

    # 先判断是否正常登录
    if request.session.get('login'):


        # 调用orm
        presslist = Press.objects.all()

        # 跳转页面 带参数
        return render(request, 'presslist.html', {'presslist': presslist})

    else:
        # 跳转页面
        return redirect('/login')

def booklist(request):
    booklist = Book.objects.all()
    return render(request, 'booklist.html', {'booklist': booklist})

def bookadd(request):
    if request.method == "GET":
        presslist = Press.objects.all()
        return render(request, 'bookadd.html', {'presslist': presslist})
    elif request.method == "POST":
        bookname = request.POST.get('bookname')
        bookprice = request.POST.get('bookprice')
        bookauthor = request.POST.get('bookauthor')
        press = request.POST.get('press')
        # 获取上传之后的文件
        bookimg_obj = request.FILES.get('bookimg')

        # print(type(bookimg_obj))
        # print(type(bookimg_obj.name))

        bookimg_name = bookimg_obj.name

        # 获取文件要保存的路径
        bookimg_path = "static/img"


        # 拼接向数据库保存的图片路径及名称
        bookimg = os.path.join(bookimg_path,bookimg_name)
        # print(bookimg)

        # 文件上传 （文件从本地复制到服务器）
        with open(bookimg, 'wb') as file:
            for xxx in bookimg_obj.chunks():
                file.write(xxx)

        bookimg = "/" + bookimg
        Book.objects.create(bookname=bookname,bookprice=bookprice,bookauthor=bookauthor,bookimg=bookimg,press_id = press)

        return redirect('/booklist')

def bookdelete(request):
    id = request.GET.get('id')
    Book.objects.filter(id=id).delete()
    return redirect('/booklist')

def bookupdate(request):
    if request.method == "GET":
        # 获取参数
        id = request.GET.get('id')

        # 调用orm - 使用get()获取单个对象
        book = Book.objects.get(id=id)
        presslist = Press.objects.all()

        # 跳转页面 修改页面 转发
        return render(request, 'bookupdate.html', {'book': book, 'presslist': presslist})
    elif request.method == "POST":
        id = request.POST.get('id')
        bookname = request.POST.get('bookname')
        bookprice = request.POST.get('bookprice')
        bookauthor = request.POST.get('bookauthor')
        press = request.POST.get('press')

        bookimg_obj = request.FILES.get('bookimg')
        # 判断bookimg_obj是否为空
        if bookimg_obj:
            bookimg_name = bookimg_obj.name
            bookimg_path = "static/img"
            bookimg = os.path.join(bookimg_path, bookimg_name)
            with open(bookimg, 'wb') as file:
                for xxx in bookimg_obj.chunks():
                    file.write(xxx)
            bookimg = "/" + bookimg
        else:
            bookimg = request.POST.get('bookimgname')



        # 真正的修改
        # 第一步：通过id找到orm对象
        book = Book.objects.get(id=id)

        # 第二步:通过orm对象（持久化对象）进行修改属性

        book.bookname = bookname
        book.bookprice = bookprice
        book.bookauthor = bookauthor
        book.bookimg = bookimg
        book.press_id = press

        # 第三步：执行持久化方法，完成修改
        book.save()
        return redirect('/booklist')

def booksearch(request):
    # 获取参数
    bookname = request.POST.get('bookname')
    # 调用orm
    booklist = Book.objects.filter(bookname__icontains=bookname)
    # 跳转页面
    return render(request, 'booklist.html', {'booklist': booklist, 'bookname': bookname})


def booktypelist(request):
    booktypelist = BookType.objects.all()
    return render(request, 'booktypelist.html', {'booktypelist': booktypelist})

def booktypeadd(request):
    if request.method == "GET":
        booklist = Book.objects.all()
        return render(request, 'booktypeadd.html', {'booklist': booklist})
    elif request.method == "POST":
        typename = request.POST.get('typename')
        bookids = request.POST.getlist('bookids')

        booktype = BookType.objects.create(typename=typename)

        # 设置中间表
        booktype.books.set(bookids)

        return redirect('/booktypelist')

def booktypeupdate(request):
    if request.method == "GET":
        # 获取参数
        id = request.GET.get('id')

        # 调用orm - 使用get()获取单个对象
        booktype = BookType.objects.get(id=id)
        # 查询所有的图书，供修改类型上复选框使用循环展示
        booklist = Book.objects.all()

        # 跳转页面 修改页面 转发
        return render(request, 'booktypeupdate.html', {'booktype': booktype, 'booklist': booklist})
    elif request.method == "POST":
        id = request.POST.get('id')
        typename = request.POST.get('typename')
        bookids = request.POST.getlist('bookids')

        # 调用 orm
        update_booktype = BookType.objects.get(id=id)

        # 设置中间表
        update_booktype.typename = typename

        update_booktype.save()

        update_booktype.books.set(bookids)
        return redirect('/booktypelist')

def booktypedelete(request):
    id = request.GET.get('id')
    BookType.objects.filter(id=id).delete()
    return redirect('/booktypelist')

def booktypesearch(request):
    # 获取参数
    typename = request.POST.get('booktypename')
    # 调用orm
    booktypelist = BookType.objects.filter(typename__icontains=typename)
    # 跳转页面
    return render(request, 'booktypelist.html', {'booktypelist': booktypelist, 'booktypename': typename})

def modalTest(request):
    return render(request, 'modalTest.html')

def booknameisexist(request):
    bookname = request.POST.get('bookname')
    # print(bookname)

    if Book.objects.filter(bookname=bookname):
        # 说明存在
        return HttpResponse("OK")
    return HttpResponse("ERROR")
def main(request):
    return render(request, 'main.html')
